#include "myhttp.h"
#include <ArduinoJson.h>
#include "protocol.h"

extern WiFiClient &GetWifiHan(void);
extern HTTPClient &GetHttpHan(void);
extern int IsWiFiRun(void);
extern int sensorValue;

void HttpDataSend(u8 *buf, u16 len)
{
  int i = 0;
  HTTPClient &ptr = GetHttpHan();
  WiFiClient &ptr_wifi = GetWifiHan();

  if (IsWiFiRun() == 0) {
    return;
  }  
  // configure traged server and url
  ptr.begin(ptr_wifi, "http://192.168.10.100:8000/data");  // HTTP
  ptr.addHeader("Content-Type", "application/json");

  Serial.print("[HTTP] POST...\n");
  // start connection and send HTTP header and body
  // 转换为json
  StaticJsonDocument<200> tranBuffer;
  auto array = tranBuffer.createNestedArray("data");
  for (i = 0; i < len; i++) {
    array.add(buf[i]);
  }

  String ouput;
  // 序列化
  serializeJsonPretty(tranBuffer, ouput);  
  int httpCode = ptr.POST((uint8_t*)ouput.c_str(),ouput.length());
  // httpCode will be negative on error
  if (httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTP] POST... code: %d\n", httpCode);

    // file found at server
    if (httpCode == HTTP_CODE_OK) {
      const String& payload = ptr.getString();
      Serial.println("received payload:\n<<");
      Serial.println(payload);
      Serial.println(">>");
    }
  } else {
    Serial.printf("[HTTP] POST... failed, error: %s\n", ptr.errorToString(httpCode).c_str());
  }
}

void HttpCmdSend(u8 *buf, u16 len)
{
  int i = 0;
  HTTPClient &ptr = GetHttpHan();
  WiFiClient &ptr_wifi = GetWifiHan();

  if (IsWiFiRun() == 0) {
    return;
  }  
  // configure traged server and url
  ptr.begin(ptr_wifi, "http://192.168.10.100:8000/resRegister");  // HTTP
  ptr.addHeader("Content-Type", "application/json");

  Serial.print("[HTTP] POST...\n");
  // start connection and send HTTP header and body
  // 转换为json
  StaticJsonDocument<200> tranBuffer;
  tranBuffer["cmdIndex"] = (u16)(buf[1] >> 8) | buf[0];
  auto array = tranBuffer.createNestedArray("dataFrame");
  for (i = 0; i < len; i++) {
    array.add(buf[i + 2]);
  }

  String ouput;
  // 序列化
  serializeJsonPretty(tranBuffer, ouput);  
  int httpCode = ptr.POST((uint8_t*)ouput.c_str(),ouput.length());
  Serial.printf("send cmdIndex:%d\r\n", (u16)(buf[1] >> 8) | buf[0]);
  for (i = 0; i < len; i++) {
     Serial.printf("data[%d]: %#x", i, ((uint8_t*)ouput.c_str())[i]);
  }
  Serial.printf("send data end\r\n");
  // httpCode will be negative on error
  if (httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTP] POST... code: %d\n", httpCode);

    // file found at server
    if (httpCode == HTTP_CODE_OK) {
      const String& payload = ptr.getString();
      Serial.println("received payload:\n<<");
      Serial.println(payload);
      Serial.println(">>");
    }
  } else {
    Serial.printf("[HTTP] POST... failed, error: %s\n", ptr.errorToString(httpCode).c_str());
  }
}

void HttpCmdGET(WiFiClient &wifiPtr, HTTPClient &httpPtr)
{
  StaticJsonDocument<200> doc;  
  u8 data[100] = {0};
  u16 len = 0;
  if (IsWiFiRun() == 0) {
    return;
  }
  if (httpPtr.begin(wifiPtr, "http://192.168.10.100:8000/cmdRegister")) {  // HTTP

    Serial.print("[HTTP] GET...\n");
    // start connection and send HTTP header
    int httpCode = httpPtr.GET();

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTP] GET... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = httpPtr.getString();
        Serial.println(payload);
        DeserializationError error = deserializeJson(doc, payload);
        u16 cmdIndex = doc["cmdIndex"];
        JsonArray array = doc["dataFrame"];
        for (int i = 0; i < array.size(); i++) {
          data[i] = array[i];
          len++;
        }
        ProtoColGetDataByHttp(ProtocolGetCtrl(), cmdIndex, data, len);
        Serial.printf("get cmdIndex :%d len:%d\r\n", cmdIndex, len);
      }
    } else { 
      Serial.printf("[HTTP] GET... failed, error: %s\n", httpPtr.errorToString(httpCode).c_str());
    }

    httpPtr.end();
  } else {
    Serial.println("[HTTP] Unable to connect");
  }
}

void HttpTask(unsigned int tick)
{
  if ((tick % 1000) == 0) {
    HttpCmdGET(GetWifiHan(), GetHttpHan());
  }

  if ((tick % 2000) == 0) {
    // HttpDataSend((u8*)&sensorValue, sizeof(sensorValue));
  }
}
